package com.huluobo.a2202mvvm_im_douyindemo.video;

import androidx.annotation.NonNull;
import androidx.lifecycle.Observer;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.PagerSnapHelper;
import androidx.recyclerview.widget.RecyclerView;

import android.content.Intent;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.animation.AccelerateInterpolator;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.EditText;

import com.blankj.utilcode.util.ToastUtils;
import com.huluobo.a2202mvvm_im_douyindemo.R;
import com.huluobo.a2202mvvm_im_douyindemo.adapter.CommentAdapter;
import com.huluobo.a2202mvvm_im_douyindemo.adapter.MultiVideoAdapter;
import com.huluobo.a2202mvvm_im_douyindemo.adapter.VideoAdapter;
import com.huluobo.a2202mvvm_im_douyindemo.bean.CommentBeanResult;
import com.huluobo.a2202mvvm_im_douyindemo.bean.VideoListBeanResult;
import com.huluobo.a2202mvvm_im_douyindemo.databinding.FragmentVideoBinding;
import com.huluobo.a2202mvvm_im_douyindemo.db.AppDBUtils;
import com.huluobo.a2202mvvm_im_douyindemo.live.LiveActivity;
import com.huluobo.a2202mvvm_im_douyindemo.mvvmBase.BaseMVVMFragment;
import com.shuyu.gsyvideoplayer.video.StandardGSYVideoPlayer;
import com.umeng.socialize.ShareAction;
import com.umeng.socialize.media.UMImage;
import com.umeng.socialize.media.UMWeb;

import java.util.ArrayList;
import java.util.List;

public class VideoFragment extends BaseMVVMFragment<FragmentVideoBinding, VideoViewModel> {

    private List<VideoListBeanResult.VideoListBean> videoListBeanLis = new ArrayList<>();

    private MultiVideoAdapter videoAdapter;

    //当前播放的是哪个item的下标
    private int currentPosition = 0;
    private StandardGSYVideoPlayer player;

    private CommentAdapter commentAdapter;

    private List<CommentBeanResult.CommentBean> commentBeanList = new ArrayList<>();


    @Override
    protected int getLayoutId() {
        return R.layout.fragment_video;
    }

    @Override
    protected void initData() {
        viewModel.getVideoList(1, 10);

        viewModel.getVideoListSuccess.observe(this, videoListBeanResult -> {
            videoAdapter.getData().addAll(videoListBeanResult.getData());
            videoAdapter.notifyDataSetChanged();
        });

        viewModel.getVideoListFailed.observe(this, s -> {
            Log.i("TagA", "获取视频列表失败:" + s);
        });

        viewModel.likeSuccess.observe(this, likeBeanResult -> {
            ToastUtils.showLong(likeBeanResult.getMessage());
            //改变数据源中的点赞为1
            videoListBeanLis.get(currentPosition).setDianzan(1);
            //刷新适配器,适配器中会自适应图标
            videoAdapter.notifyItemChanged(currentPosition);
        });

        viewModel.likeFailed.observe(this, s -> {
            Log.i("TagA", "点赞失败:" + s);
        });

        viewModel.noLikeSuccess.observe(this, likeBeanResult -> {
            ToastUtils.showLong(likeBeanResult.getMessage());
            videoListBeanLis.get(currentPosition).setDianzan(0);
            videoAdapter.notifyItemChanged(currentPosition);
        });

        viewModel.noLikeFailed.observe(this, s -> {
            Log.i("TagA", "取消点赞失败:" + s);
        });

        viewModel.followAuthSuccess.observe(this, followBeanResult -> {
            ToastUtils.showLong(followBeanResult.getMessage());
            if (followBeanResult.getCode() == 200) {
                videoAdapter.getData().get(currentPosition).setGuanzhu(1);
                videoAdapter.notifyItemChanged(currentPosition);
            }
        });

        viewModel.followAuthFailed.observe(this, s -> {
            Log.i("TagA", "关注失败:" + s);
        });

        viewModel.getCommentSuccess.observe(this, commentBeanResult -> {
            if (commentBeanResult.getCode() == 200) {
                commentBeanList.clear();
                commentBeanList.addAll(commentBeanResult.getData());
                commentAdapter.notifyDataSetChanged();
            } else {
                ToastUtils.showLong(commentBeanResult.getMessage());
            }
        });

        viewModel.getCommentFailed.observe(this, s -> {
            Log.i("TagA", "获取评论列表失败:" + s);
        });

        viewModel.sendCommentSuccess.observe(this, commentBeanResult -> {
            if (commentBeanResult.getCode() == 200) {
                //在评论列表的第0位添加最新的评论
                commentAdapter.getData().addAll(0, commentBeanResult.getData());
                commentAdapter.notifyDataSetChanged();

                EditText editText = (EditText) videoAdapter.getViewByPosition(currentPosition,
                        R.id.item_video_input_et);
                assert editText != null;
                editText.setText("");
            }
        });

        viewModel.sendCommentFailed.observe(this, s -> {

        });
    }

    @Override
    protected void initView() {
        LinearLayoutManager layoutManager = new LinearLayoutManager(requireContext());
        dataBinding.videoRv.setLayoutManager(layoutManager);
        videoAdapter = new MultiVideoAdapter();
        dataBinding.videoRv.setAdapter(videoAdapter);

        PagerSnapHelper pagerSnapHelper = new PagerSnapHelper();
        pagerSnapHelper.attachToRecyclerView(dataBinding.videoRv);

        dataBinding.videoRv.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
                //当RecyclerView滚动后的回调
                currentPosition = layoutManager.findFirstVisibleItemPosition();
                player = (StandardGSYVideoPlayer) videoAdapter.getViewByPosition(currentPosition,
                        R.id.item_video_gsyPlayer);
//                if (player != null) {
//                    player.startPlayLogic();
//                }
            }
        });
        //设置adapter中点击事件的前提,需要设置item中的view可点
        videoAdapter.addChildClickViewIds(R.id.item_video_like_iv, R.id.item_video_add_iv, R.id.item_video_comment_iv
                , R.id.item_video_close_iv, R.id.item_video_send_iv, R.id.item_video_share_iv,
                R.id.item_video_follow_iv, R.id.item_video_full_cl, R.id.item_video_live_cl);

        //设置item的点击事件
        videoAdapter.setOnItemChildClickListener((adapter, view, position) -> {
            //拿到当前播放的视频bean
            VideoListBeanResult.VideoListBean videoListBean =
                    (VideoListBeanResult.VideoListBean) adapter.getData().get(position);
            switch (view.getId()) {
                case R.id.item_video_like_iv:
                    likeVideo(videoListBean);
                    break;
                case R.id.item_video_add_iv:
                    followAuth(videoListBean);
                    break;
                case R.id.item_video_comment_iv:
                    openComment(videoListBean);
                    break;
                case R.id.item_video_close_iv:
                    closeComment();
                    break;
                case R.id.item_video_send_iv:
                    sendComment(videoListBean);
                    break;
                case R.id.item_video_share_iv:
                    shareVideo(videoListBean);
                    break;
                case R.id.item_video_follow_iv:
                    followVideo(videoListBean);
                    break;
                case R.id.item_video_full_cl:
                    fullScreenPlayer(videoListBean);
                    break;
                case R.id.item_video_live_cl:
                    toLive(videoListBean);
                    break;
            }
        });
    }

    //跳转直播间
    private void toLive(VideoListBeanResult.VideoListBean videoListBean) {
        Intent intent = new Intent(requireContext(), LiveActivity.class);
        intent.putExtra("videoBean", videoListBean);
        startActivity(intent);
    }

    //设置全屏
    private void fullScreenPlayer(VideoListBeanResult.VideoListBean videoListBean) {
        if (player != null) {
            player.setRotateViewAuto(true);//自动翻转屏幕
            player.startWindowFullscreen(requireContext(), false, false);//设置全屏,是否显示总做条,是否显示状态栏
            player.startPlayLogic();
        }
    }

    private void followVideo(VideoListBeanResult.VideoListBean videoListBean) {
        AppDBUtils.getInstance().getVideoDao().insertVideoInfo(videoListBean);
    }

    //分享
    private void shareVideo(VideoListBeanResult.VideoListBean videoListBean) {
        //缩略图
        UMImage umImage = new UMImage(requireContext(), videoListBean.getVideomainimg());
        umImage.compressStyle = UMImage.CompressStyle.SCALE;//压缩图片大小

        UMWeb web = new UMWeb(videoListBean.getVideopath());//分享视频地址
        web.setTitle(videoListBean.getAuthname());//分享标题
        web.setThumb(umImage);//设置缩略图
        web.setDescription(videoListBean.getCaption());//设置描述

        new ShareAction(requireActivity())
                .withMedia(web)
                .open();
    }

    //发送评论
    private void sendComment(VideoListBeanResult.VideoListBean videoListBean) {
        //拿到输入框
        EditText editText = (EditText) videoAdapter.getViewByPosition(currentPosition, R.id.item_video_input_et);
        assert editText != null;
        String sendMsg = editText.getText().toString();
        if (TextUtils.isEmpty(sendMsg)) {
            ToastUtils.showLong("请输入评论内容");
            return;
        }
        viewModel.sendComment(sendMsg, videoListBean.getId());
    }

    //关闭评论列表
    private void closeComment() {
        View commentLayout = videoAdapter.getViewByPosition(currentPosition, R.id.item_video_comment_ll);
        Animation animationOut = AnimationUtils.loadAnimation(requireContext(), R.anim.anim_out);
        animationOut.setDuration(500);
        animationOut.setInterpolator(new AccelerateInterpolator());
        animationOut.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {

            }

            @Override
            public void onAnimationEnd(Animation animation) {
                assert commentLayout != null;
                commentLayout.setVisibility(View.GONE);
                dataBinding.videoRv.setIntercept(true);
            }

            @Override
            public void onAnimationRepeat(Animation animation) {

            }
        });
        assert commentLayout != null;
        commentLayout.startAnimation(animationOut);
    }

    //打开评论列表
    private void openComment(VideoListBeanResult.VideoListBean videoListBean) {
        //展示评论列表的时候,拦截RecyclerView的事件
        dataBinding.videoRv.setIntercept(false);
        //拿到评论布局
        View commentLayout = videoAdapter.getViewByPosition(currentPosition, R.id.item_video_comment_ll);
        assert commentLayout != null;
        commentLayout.setVisibility(View.VISIBLE);

        Animation animation = AnimationUtils.loadAnimation(requireContext(), R.anim.anim_in);
        animation.setDuration(500);
        animation.setInterpolator(new AccelerateInterpolator());
        animation.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {
                viewModel.getComment(videoListBean.getId());
            }

            @Override
            public void onAnimationEnd(Animation animation) {

            }

            @Override
            public void onAnimationRepeat(Animation animation) {

            }
        });
        commentLayout.startAnimation(animation);

        //初始化评论列表
        RecyclerView commentRv = (RecyclerView) videoAdapter.getViewByPosition(currentPosition,
                R.id.item_video_comment_rv);
        assert commentRv != null;
        commentRv.setLayoutManager(new LinearLayoutManager(requireContext()));
        commentAdapter = new CommentAdapter(commentBeanList);
        commentRv.setAdapter(commentAdapter);
    }

    //关注作者
    private void followAuth(VideoListBeanResult.VideoListBean videoListBean) {
        viewModel.followAuth(videoListBean.getAuthname());
    }

    //点赞与取消点赞
    private void likeVideo(VideoListBeanResult.VideoListBean videoListBean) {
        if (videoListBean.getDianzan() == 0) {
            //未点赞,需要触发点赞的方法
            viewModel.likeVideo(videoListBean.getId());
        } else {
            //已点赞,需要出发取消点赞的方法
            viewModel.noLikeVideo(videoListBean.getId());
        }
    }

    @Override
    protected Class<VideoViewModel> getViewModel() {
        return VideoViewModel.class;
    }
}